package com.jp.knowledge.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.google.gson.internal.LinkedTreeMap;
import com.jiayen.util.ToasUtil;
import com.jiayen.view.VerifyCodeView;
import com.jp.knowledge.R;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.command.CommandInvoker;
import com.jp.knowledge.command.CommandReceiver;
import com.jp.knowledge.command.implement.GangWeiZhiShiPaiXu;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.logic.PersonLogic;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.util.SharedUtil;

public class LoginSecondActivity extends SlidingActivity implements
        View.OnClickListener, ResultSubscriber.OnResultListener, JpApplication.SendMsgTimerCallBack {

    private final int LOGIN_CODE = 0x000001;//登录
    private final int VERIFY_CODE = 0x000002;//获取验证码
    private final int USER_DETAIL_CODE = 0x000003;//获取用户信息
    private final int VOICE_VERIFY_CODE = 0x000004;//获取语音验证码

    protected VerifyCodeView smsCode;
    private TextView smsCodeBtn;
    private TextView voiceCodeBtn;
    protected String phone;
    private LocalBroadcastManager localManager;
    private PersonLogic personLogic;
    private TextView tipCode;//验证码提示

    @Override
    protected int getResourceId() {
        return R.layout.activity_login_second;
    }

    @Override
    protected void init() {

        localManager = LocalBroadcastManager.getInstance(mContext);

        application.putLoginActivity(this);
        phone = getIntent().getStringExtra("phone");
        rightIcon.setVisibility(View.GONE);
        topDesc.setVisibility(View.GONE);
        topName.setText("登录");
        topName.setCompoundDrawables(null, null, null, null);
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        leftIcon.setOnClickListener(this);

        smsCode = (VerifyCodeView) findViewById(R.id.phone_code);
        smsCodeBtn = (TextView) findViewById(R.id.sms_code);
        smsCodeBtn.setOnClickListener(this);

        voiceCodeBtn = (TextView) findViewById(R.id.voice_code);
        voiceCodeBtn.setOnClickListener(this);

        tipCode = (TextView) findViewById(R.id.code_tip);
        timerCallBack(application.getNextSendMsgTime());
        smsCode.setListener(new VerifyCodeView.CompleteListener() {
            @Override
            public void done() {
                login();
            }
        });
    }

    /* 执行登录 */
    protected void login() {
        JsonObject param = new JsonObject();
        param.addProperty("phone", phone);
        param.addProperty("verifyCode", smsCode.getVerifyCodeStr());
        HttpHelper.getInstance(mContext).login(param, LOGIN_CODE, this);
    }

    private long preClickTime;      // 防止多次重复点击
    @Override
    public void onClick(View view) {
        long currentTime = System.currentTimeMillis();
        if(currentTime - preClickTime < 500){
            preClickTime = currentTime;
            return;
        }
        preClickTime = currentTime;

        if (view.getId() == R.id.sms_code) {
            JsonObject param = new JsonObject();
            param.addProperty("phone", phone);
            HttpHelper.getInstance(mContext).getSmsCode(param, VERIFY_CODE, this);
        } else if(view == voiceCodeBtn){
            JsonObject param = new JsonObject();
            param.addProperty("token", HttpHelper.token);
            param.addProperty("phone", phone);
            HttpHelper.getInstance(mContext).getVoiceCode(param, VOICE_VERIFY_CODE, this);
        } else if(view == leftIcon){
            this.finish();
        }
    }

    @Override
    public void onStart(int requestType) {
        showLoading();
    }
    @Override
    public void onCompleted(int requestType) {
        cancleLoading();
    }
    @Override
    public void onError(int requestType) {}
    @Override
    public void onNext(IModel data, int requestType) {
        int code = data.getErrcode();
//        if (code == 110106) {//验证码错误
//            tipCode.setVisibility(View.VISIBLE);
//        } else if (code != 0) {
//            ToasUtil.toast(this, data.getMessage());
//            return;
//        }
        if (requestType == LOGIN_CODE) {//登录
            if(code==0) {
                LinkedTreeMap<String, String> map = (LinkedTreeMap<String, String>) data.getData();
                HttpHelper.token = map.get("token");
                HttpHelper.uuid = map.get("secuCode");
                SharedUtil.getInstance(mContext).saveTokenAndUUId(HttpHelper.token, HttpHelper.uuid);
                ToasUtil.toast(mContext, "登录成功");
                application.IS_LOGIN = true;//记录登录
                //获取用户信息
                getUserData();
            }else{
                smsCode.clearVerifyCode();
                tipCode.setVisibility(View.VISIBLE);
                tipCode.setText(data.getMessage());
                ToasUtil.toast(mContext, data.getMessage());
            }

        } else if (requestType == VERIFY_CODE) {//获取验证码成功
            startTimer();
            ToasUtil.toast(mContext, "请1分钟后再试语言验证码");
        } else if (requestType == USER_DETAIL_CODE) {//获取用户信息
            if (code == 0) {//获取用户信息成功

            } else {//获取用户信息失败重新请求

            }
        } else if (requestType == VOICE_VERIFY_CODE) {//获取语音验证码成功
            startTimer();
            ToasUtil.toast(mContext, "你马上将收到来电播放验证码");
        }
    }

    /* 发送登录成功广播 */
    private void sendLoginSuccessBroad() {
        Intent intent =  new Intent(LocalBroadCast.LOGIN_SUCCESS_BROD);
        localManager.sendBroadcast(intent);

        SharedPreferences sp = getSharedPreferences("loginMessage", MODE_PRIVATE);
        if(!sp.getBoolean("hadLogin", false)) {
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("hadLogin", true);
            editor.apply();
            // 首次登录
//            CommandInvoker.executeCommand(new GangWeiZhiShiPaiXu(new CommandReceiver(mContext)));
//            localManager.sendBroadcast(new Intent(LocalBroadCast.FIRST_LOGIN));
        }
    }

    /*  获取用户信息 */
    private void getUserData() {
//        JsonObject param = new JsonObject();
//        HttpHelper.getInstance(context).userDetail(param, USER_DETAIL_CODE, this);
        loading.show();
        personLogic= new PersonLogic(mContext, new PersonLogic.UserDataCallBack() {
            @Override
            public void done(UserData userData) {
                if(userData!=null){//获取用户信息成功  才代表登录成功
                    //发送登录广播通知登录后需要获取的信息(目前是针对雷达)
                    sendLoginSuccessBroad();
                    application.closeLoginActivity();
                }
            }
        });
        personLogic.getUserData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        application.setTimerCallBack(this);
        timerCallBack(application.getNextSendMsgTime());
    }

    @Override
    public void timerCallBack(int time) {
        if(time > 0){
            smsCodeBtn.setText("重新获取(" + time + "秒)");
        } else {
            smsCodeBtn.setTextColor(getResources().getColor(R.color.theme_color));
            smsCodeBtn.setText("重新获取");
            smsCodeBtn.setEnabled(true);
            voiceCodeBtn.setTextColor(getResources().getColor(R.color.theme_color));
            voiceCodeBtn.setEnabled(true);
        }
    }

    private void startTimer(){
        voiceCodeBtn.setEnabled(false);
        voiceCodeBtn.setTextColor(getResources().getColor(R.color.font_gray_think));
        smsCodeBtn.setEnabled(false);
        smsCodeBtn.setTextColor(getResources().getColor(R.color.gray));
        tipCode.setVisibility(View.GONE);

        application.setNextSendMsgTime(60);
        timerCallBack(application.getNextSendMsgTime());
        application.startTimerCountdown();
    }

}